﻿// LoginDialog.cpp: 实现文件
//

#include "stdafx.h"
#include "LoginDialog.h"
#include "afxdialogex.h"
#include "RegisterDlg.h"
#include "resource.h"
#include "myUtil.h"
#include <iostream>
#include <fstream>
using namespace std;

// LoginDialog 对话框

IMPLEMENT_DYNAMIC(LoginDialog, CDialogEx)

LoginDialog::LoginDialog(CWnd* pParent /*=nullptr*/)
	: CDialogEx(DLG_LOGIN, pParent)
{
	workingGroup = -1;
	workingName = L"";
	testSet = L"";
	pLoginDB = nullptr;



}

LoginDialog::~LoginDialog()
{
}

BOOL LoginDialog::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	string tmp;
	ifstream is("testSetList.txt");
	int idx = 0;
	if (is.is_open())
	{
		while (!is.eof())
		{
			tmp = "";
			is >> tmp;
			if (tmp != "")
			{
				mTestSetSel.InsertString(idx, CString(tmp.c_str()));
				idx++;
			}
		}
	}
	else
	{
		mTestSetSel.InsertString(0, L"默认测试设备");
	}
	mTestSetSel.SetWindowTextW(L"请选择测试设备");
	return true;
}


void LoginDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, EDT_LOGIN_NAME, m_name);
	DDX_Control(pDX, EDT_LOGIN_PASSWORD, m_password);
	DDX_Control(pDX, IDC_TestSetSelCom, mTestSetSel);
}


BEGIN_MESSAGE_MAP(LoginDialog, CDialogEx)
	ON_BN_CLICKED(BTN_LOGIN, &LoginDialog::OnBnClickedLogin)
	ON_BN_CLICKED(BTN_REGISTER, &LoginDialog::OnBnClickedRegister)
	ON_BN_CLICKED(IDCANCEL, NULL)
	ON_BN_CLICKED(IDC_BUTTON1, &LoginDialog::OnBnClickedButton1)
END_MESSAGE_MAP()


// LoginDialog 消息处理程序


void LoginDialog::OnBnClickedLogin()
{
	// TODO: 在此添加控件通知处理程序代码

	//获取数据
	UpdateData(TRUE);
	CString inputName;
	m_name.GetWindowTextW(inputName);
	CString inputPwd;
	m_password.GetWindowTextW(inputPwd);

	if (inputName == L"" || inputPwd == L"")
	{
		AfxMessageBox(L"请输入完整");
		return;
	}
	mTestSetSel.GetWindowTextW(testSet);
	string strname = CT2A(inputName.GetBuffer());
	string strpwd = CT2A(inputPwd.GetBuffer());

	int userGroup = pLoginDB->getAuthRight(strname, strpwd);
	
	//todo only for test need remove when release.
	if (strname == "chenjiangbo" && strpwd == "1q2w3e4r")
		userGroup = 99;

	if(userGroup > 0)
	{
		workingGroup = userGroup;
		workingName = inputName;
		CDialogEx::OnOK();
	}
	else
	{
		AfxMessageBox(L"输入错误或不存在");
	}
}


void LoginDialog::OnBnClickedRegister()
{
	// TODO: 在此添加控件通知处理程序代码

	ShowWindow(SW_HIDE);

	//新建注册窗口类
	RegisterDlg dlgRegister;
	dlgRegister.pRegisterDB = pLoginDB;
	//模态对话框，返回值传递给EndDialog的参数
	INT_PTR nRet = dlgRegister.DoModal();
	if (nRet == IDOK)
	{
		//创建文件
		CStdioFile file(L"user.dat", CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite);
		AfxMessageBox(L"注册成功!");
	}
	ShowWindow(SW_SHOWNORMAL);
}


void LoginDialog::OnBnClickedButton1()
{
	workingGroup = -2;
	CDialogEx::OnOK();
}

void LoginDialog::OnOK()
{
	if (workingGroup == -1)
	{
		OnBnClickedLogin();
	}
	else
	{
		CDialogEx::OnOK();
	}
}
